<template>
  <van-form @submit="onSubmit">
    <van-field
      v-model="username"
      class="login_input"
      name="用户名"
      label="username"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="password"
      class="login_input"
      type="password"
      name="密码"
      label="password"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <div style="margin: 16px">
      <van-button
        v-if="loginStatus == 1"
        round
        block
        type="primary"
        @click="handleLogin"
        >登录</van-button
      >
      <van-button v-else round block type="primary" @click="handleRegister"
        >注册</van-button
      >
    </div>
    <p class="form_bottom">
      <span v-on:click="changeStatus">{{
        loginStatus == 1 ? "去注册" : "去登录"
      }}</span>
    </p>
  </van-form>
</template>

<script lang='ts'>
import { tologin, toRegister } from "@/api/api";
import { useRouter } from "vue-router";
import { Vue, Options } from "vue-class-component";
import { Toast } from "vant";
import { useStore } from "vuex";
@Options({
  components: {},
})
export default class login extends Vue {
  username: string = "李志伟";
  password: string = "123456";
  loginStatus: number = 1;

  router = useRouter(); //路由对象，用来进行路由跳转

  store: any = useStore(); //仓库对象

  handleLogin(): void {
    const query = {
      username: this.username,
      password: this.password,
    };
    tologin(query).then((res: any) => {
      if (res.data.code == 1) {
        Toast({
          message: res.data.msg,
          icon: "passed",
        });
        this.store.commit("userInfo/SET_TOKEN", res.data.token);
        this.store.commit("userInfo/SET_USERNAME", res.data.username);
        this.store.commit("userInfo/SET_PASSWORD", res.data.password);
        this.router.replace('/');
      } else {
        Toast({
          message: res.data.msg,
          icon: "info-o",
        });
      }
    });
  }

  handleRegister(): void {
    const query = {
      username: this.username,
      password: this.password,
    };

    toRegister(query).then((res: any) => {
      if (res.data.code == 1) {
        Toast({
          message: res.data.msg,
          icon: "passed",
        });
        this.loginStatus = 1
      } else {
        Toast({
          message: res.data.msg,
          icon: "info-o",
        });
      }
    });
  }

  changeStatus(): void {
    this.loginStatus = this.loginStatus == 1 ? 2 : 1;
  }
}
</script>

<style scoped lang='scss'>
@import "../assets/common/login.scss";
</style>